package com.gongsir.controller;

import com.gongsir.entity.User;
import com.gongsir.service.UserService;
import com.gongsir.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 龚涛
 * @date 2020/8/17 15:18
 * 编码不要畏惧变化，要拥抱变化
 * 处理来自前端的请求, 使用controller注解
 */
@Controller
@RequestMapping("/auth")
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param request request
     * @return mv
     */
    @PostMapping("/login")
    public ModelAndView login(String username, String password, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        mv.clear();
        HttpSession session = request.getSession();
        log.info("用户登录:[username:{"+username+"}, password:{"+password+"}]");
        // get user by username from db
        User user = userService.getUserByUsername(username);
        if (null != user) {
            // 数据库的密码是md5签名密码, 需将用户输入的密码进行签名再进行比对
            if (MD5Util.md5(password).equals(user.getPassword())) {
                // password right
                // 将用户信息存入session
                session.setAttribute("admin",user);
                mv.setViewName("index");
                mv.addObject("msg","登陆成功");
            } else {
                // password error
                mv.setViewName("login");
                mv.addObject("msg","密码错误");
            }
        } else {
            // username error
            mv.setViewName("login");
            mv.addObject("msg","用户名错误");
        }
        return mv;
    }

    /**
     * 退出登录
     * @param request request, 清除Session
     * @return string
     */
    @GetMapping(path = "/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("admin");
        return "login";
    }
}
